<template>
<!--  <div class="role-management">-->
<!--    <el-button v-permission="'system:role:add'" type="primary" @click="showAddDialog">新增</el-button>-->
<!--    <el-table :data="roleList" border style="margin-top: 20px;">-->
<!--      <el-table-column prop="roleName" label="角色名称" />-->
<!--      <el-table-column prop="roleKey" label="权限字符串" />-->
<!--      <el-table-column prop="status" label="状态">-->
<!--        <template #default="{ row }">-->
<!--          {{ row.status === '0' ? '正常' : '停用' }}-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="操作" width="200">-->
<!--        <template #default="{ row }">-->
<!--          <el-button v-permission="'system:role:edit'" type="text" @click="showEditDialog(row)">编辑</el-button>-->
<!--          <el-button v-permission="'system:role:delete'" type="text" @click="deleteRole(row.id)">删除</el-button>-->
<!--          <el-button v-permission="'system:role:assign'" type="text" @click="showAssignDialog(row)">分配权限</el-button>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--    </el-table>-->

<!--    &lt;!&ndash; 新增/编辑对话框 &ndash;&gt;-->
<!--    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="30%">-->
<!--      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">-->
<!--        <el-form-item label="角色名称" prop="roleName">-->
<!--          <el-input v-model="form.roleName" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="权限字符串" prop="roleKey">-->
<!--          <el-input v-model="form.roleKey" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="状态" prop="status">-->
<!--          <el-radio-group v-model="form.status">-->
<!--            <el-radio label="0">正常</el-radio>-->
<!--            <el-radio label="1">停用</el-radio>-->
<!--          </el-radio-group>-->
<!--        </el-form-item>-->
<!--      </el-form>-->
<!--      <template #footer>-->
<!--        <el-button @click="dialogVisible = false">取消</el-button>-->
<!--        <el-button type="primary" @click="submitForm">确定</el-button>-->
<!--      </template>-->
<!--    </el-dialog>-->

<!--    &lt;!&ndash; 分配权限对话框 &ndash;&gt;-->
<!--    <el-dialog title="分配权限" v-model="assignDialogVisible" width="30%">-->
<!--      <el-tree-->
<!--          ref="menuTree"-->
<!--          :data="menuList"-->
<!--          show-checkbox-->
<!--          node-key="id"-->
<!--          :default-checked-keys="checkedMenuIds"-->
<!--          :props="{ label: 'menuName', children: 'childrenMenus' }"-->
<!--          check-strictly-->
<!--      />-->
<!--      <template #footer>-->
<!--        <el-button @click="assignDialogVisible = false">取消</el-button>-->
<!--        <el-button type="primary" @click="saveMenus">确定</el-button>-->
<!--      </template>-->
<!--    </el-dialog>-->
<!--  </div>-->
  角色
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';

const roleList = ref([]);
const menuList = ref([]);
const dialogVisible = ref(false);
const assignDialogVisible = ref(false);
const dialogTitle = ref('');
const currentRoleId = ref(null);
const checkedMenuIds = ref([]);
const form = ref({
  id: null,
  roleName: '',
  roleKey: '',
  status: '0'
});
const formRef = ref(null);
const rules = {
  roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
  roleKey: [{ required: true, message: '请输入权限字符串', trigger: 'blur' }]
};

const fetchRoles = async () => {
  const res = await axios.get('/api/system/role/list', {
    headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
  });
  roleList.value = res.data;
};

const fetchMenus = async () => {
  const res = await axios.get('/api/system/menu/tree', {
    headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
  });
  menuList.value = res.data;
};

const showAddDialog = () => {
  form.value = {
    id: null,
    roleName: '',
    roleKey: '',
    status: '0'
  };
  dialogTitle.value = '新增角色';
  dialogVisible.value = true;
};

const showEditDialog = async (row) => {
  const res = await axios.get(`/api/system/role/${row.id}`, {
    headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
  });
  form.value = { ...res.data };
  dialogTitle.value = '编辑角色';
  dialogVisible.value = true;
};

const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      const data = { ...form.value };
      if (data.id) {
        await axios.put('/api/system/role', data, {
          headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
        });
        ElMessage.success('更新成功');
      } else {
        await axios.post('/api/system/role', data, {
          headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
        });
        ElMessage.success('添加成功');
      }
      dialogVisible.value = false;
      fetchRoles();
    }
  });
};

const deleteRole = async (id) => {
  try {
    await axios.delete(`/api/system/role/${id}`, {
      headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
    });
    ElMessage.success('删除成功');
    fetchRoles();
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '删除失败');
  }
};

const showAssignDialog = async (row) => {
  currentRoleId.value = row.id;
  const res = await axios.get(`/api/system/role/${row.id}/menuIds`, {
    headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
  });
  checkedMenuIds.value = res.data;
  assignDialogVisible.value = true;
};

const saveMenus = async () => {
  const menuIds = menuTree.value.getCheckedKeys();
  await axios.post('/api/system/role/assignMenus', { roleId: currentRoleId.value, menuIds }, {
    headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
  });
  ElMessage.success('权限分配成功');
  assignDialogVisible.value = false;
  fetchRoles();
};

onMounted(() => {
  fetchRoles();
  fetchMenus();
});
</script>

<style scoped>
.role-management {
  padding: 20px;
}
</style>